const mysql = require("mysql");
const oracledb = require("oracledb");
const mongodb = require("mongodb");
const db = require("../conf/db");
/*
try {
  oracledb.initOracleClient({
    libDir: "E:\\software package\\odacinstant\\client_11_2",
  });
} catch (err) {
  console.error("Whoops!");
  console.error(err);
  process.exit(1);
}
*/
/*
const db = {
  pytrol: {
    host: "localhost",
    port: 3306,
    database: "pytrol",
    user: "root",
    password: "123qweasdzxc",
  },
  oracle: {
    user: "XINXI",
    password: "XINXI",
    connectString:
      "(DESCRIPTION =  (ADDRESS = (PROTOCOL = TCP)(HOST = 10.76.19.33)(PORT = 2520)) (CONNECT_DATA =(SERVICE_NAME = oraunix)))",
    //poolAlias: "ass2013",
  },
};
*/

class mysqlpool {
  constructor() {
    this.pool = mysql.createPool(db.pytrol);
  }

  async query(sql) {
    if (sql && this.pool)
      return new Promise((resolve, reject) => {
        this.pool.getConnection((err, conn) => {
          if (err) {
            reject(err);
          } else {
            conn.query(sql, async (err, res) => {
              if (err) {
                reject(err);
                //resolve({ errnum: err2.errorNum, message: err2.message });
              } else {
                resolve(res);
                //resolve(JSON.stringify(res));
              }
              conn.release();
            });
          }
        });
      });
  }
}
class oraclepool {
  constructor() {
    //this.pool = oracledb.createPool(db.oracle);

    oracledb
      .createPool(db.oracle)
      .catch((err) => (this.poolerr = err))
      .then((pool) => {
        this.pool = pool;
        console.log("oracle-pool", typeof this.pool.con);
      });
    /*
    (err, pool) => {
      if (err) {
        this.poolerr = err;
      }
      if (pool) {
        this.pool = pool;
      }
    };
    */
  }

  async query(sql) {
    if (sql && this.pool)
      return new Promise(async (resolve, reject) => {
        this.pool.getConnection((err, conn) => {
          if (err) {
            reject(err);
          } else {
            conn.execute(sql, async (err, res) => {
              if (err) {
                reject(err);
                //resolve({ errnum: err2.errorNum, message: err2.message });
              } else {
                //resolve(JSON.stringify(res));
                resolve(res);
              }
              conn.release();
            });
          }
        });
      });
  }
}

const mongodbpool = new mongodb.MongoClient(db.mongodb.url, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  serverApi: mongodb.ServerApiVersion.v1,
});
/*
    client.connect((err) => {
      const collection = client.db("test").collection("devices");
      // perform actions on the collection object
      client.close();
    });
*/
const pytrolpool = new mysqlpool();
const asspool = new oraclepool();

module.exports = { asspool, pytrolpool, mongodbpool };
